package com.zj.intercept;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class MyInterceptor implements HandlerInterceptor {

    private static Logger log= LoggerFactory.getLogger(MyInterceptor.class);

    public MyInterceptor(){
        System.out.println("MyInterceptor ===================================");
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("requestTime", LocalDateTime.now());
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        LocalDateTime time = (LocalDateTime)request.getAttribute("requestTime");
        long cost= Duration.between(time,LocalDateTime.now()).toMillis();
        String requestURI = request.getRequestURI();
        log.info("resquest trime:"+time+",request uri:"+requestURI+",request cost:"+cost);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
